import os, sys, time, asyncio, aiohttp

import re

import pymysql
import tqdm

FLAGS = ("http://download.apk3.com/soft/201503/elsfkyxzlpjb13.apk"
         , "http://download.apk3.com/soft/201503/rywgOLpjb10.apk"
         , "http://download.apk3.com/soft/201503/btw3dxgb200.apk"
         , "http://download.apk3.com/soft/201503/jdzjfktwxgb10.apk"
         , "http://download.apk3.com/soft/201503/smtlzpjb15.apk"
         , "http://download.apk3.com/soft/201503/byhxgb10.apk"
         , "http://download.apk3.com/soft/201503/gzbxspjb10.apk"
         , "http://download.apk3.com/soft/201503/pplaxcpjb120.apk"
         , "http://download.apk3.com/soft/201503/gwcqpjb10.apk"
         , "http://download.apk3.com/soft/201503/qxpkbxxgb10.apk"
         , "http://download.apk3.com/soft/201503/xsqsdpjb130.apk"
         , "http://download.apk3.com/soft/201503/jbsdxgb80.apk"
         , "http://download.apk3.com/soft/201503/xddtxgb23.apk"
         , "http://download.apk3.com/soft/201503/ftgdmxhdxgb5125.apk"
         , "http://download.apk3.com/soft/201603/ttdgzxgb10.apk"
         , "http://download.apk3.com/soft/201503/mpcypjb10.apk"
         , "http://download.apk3.com/soft/201503/yxlmglzsxgb12.apk"
         , "http://download.apk3.com/soft/201503/zdzy2xgb234.apk"
         )
# 保存目录
DEST_DIR = 'downloads/'
headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.13 Safari/537.36',
    "Referer": "http://www.v2ex.com/signin"
}


# 获取链接,下载文件
async def fetch(session: aiohttp.ClientSession, url: str, path: str, flag: str):
    async with session.get(url, headers=headers, timeout=5000) as resp:
        with open(path, 'wb') as fd:
            while 1:
                chunk = await resp.content.read(1024)  # 每次获取1024字节
                if not chunk:
                    break
                fd.write(chunk)
    return flag


async def begin_download(sem, session: aiohttp.ClientSession, url: str, path: str, flag: str):
    # 控制协程并发数量
    with (await sem):
        return await fetch(session, url, path, flag)


async def download(sem: asyncio.Semaphore):
    tasks = []
    async with aiohttp.ClientSession() as session:
        for flag in FLAGS:
            # 创建路径以及url
            path = os.path.join(DEST_DIR, '%s.apk' % ((flag[35:40]).replace("/", "")))
            # 构造一个协程列表
            tasks.append(asyncio.ensure_future(begin_download(sem, session, flag, path, flag)))
        # 等待返回结果
        tasks_iter = asyncio.as_completed(tasks)
        # 创建一个进度条
        fk_task_iter = tqdm.tqdm(tasks_iter, total=len(FLAGS))
        for coroutine in fk_task_iter:
            res = await coroutine
            print(res, '下载完成')


# 查询上次最后一次的序号
def selectNo(cursor):
    cursor.execute("select *  from apk3 where _id=(select max(_id)  from apk3)")
    maxNO = cursor.fetchall()
    if maxNO.__len__() > 0:
        firstNo = maxNO[0][1]
        return int(firstNo) + 1
    return 0

# http://www.pc6.com/softview/SoftView_599214.html
# http://www.pc6.com/softview/SoftView_105609.html
# http://www.pc6.com/softview/SoftView_599492.html
# 更新已下载的地址
def updateP(address):
    sql = "update  apk3 set isDown=1  where downAddress=%s" % address


def selectDownAddress():
    cursor.execute("select *  from apk3 where isDown= ")


# 插入序号
def installNO(cursor, db, NO, appName="", downAddress=""):
    # 'insert into apk3(NO,appName,downAddress) values (277982,星王高爆版下载 5.0,https://dlres.63yx.com/h5zy/10111-721343/xwgbb.apk)'
    sql = "insert into apk3(No,appName,downAddress) values (%d,'%s','%s')" % (NO, appName, downAddress)
    cursor.execute(sql)
    db.commit()
    db.rollback()


if __name__ == '__main__':
    db = pymysql.connect("localhost", "root", "164531", "appmsg")
    cursor = db.cursor()
    # 创建目录
    os.makedirs(DEST_DIR, exist_ok=True)
    # 获取事件循环
    lp = asyncio.get_event_loop()
    start = time.time()
    # 创建一个信号量以防止DDos
    sem = asyncio.Semaphore(4)
    lp.run_until_complete(download(sem))
    end = time.time()
    lp.close()
    print('共耗时:', end - start)
    print("完")
